//
//  FNMockConfigViewController.m
//  MockServer
//
//  Created by caoyq on 2021/2/9.
//

#import "FNMockConfigViewController.h"
#import "FNMockManager.h"

@interface FNMockConfigViewController ()<NSURLSessionDataDelegate>

/// 服务器地址输入框
@property (weak, nonatomic) IBOutlet UITextView *inputDomainView;
/// 匹配文件相对路径输入框
@property (weak, nonatomic) IBOutlet UITextView *inputMapView;
/// mock 开关
@property (weak, nonatomic) IBOutlet UISwitch *switchBtn;
/// 更新配置按钮
@property (weak, nonatomic) IBOutlet UIButton *updateButton;


@property (nonatomic, strong) UIActivityIndicatorView *indicatorView;
 
@property (nonatomic, strong) NSMutableData *responseData;

@end

@implementation FNMockConfigViewController

- (instancetype)init {
    NSString *nibName = NSStringFromClass([self class]);
    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    return [super initWithNibName:nibName bundle:bundle];
}

#pragma mark -

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"Mock";
    self.responseData = [NSMutableData data];
    
    // 展示本地配置
    self.inputDomainView.text = [FNMockManager shareInstance].domain;
    self.inputMapView.text = [FNMockManager shareInstance].mapPath;
    self.switchBtn.on = [FNMockManager shareInstance].isMock;
}

#pragma mark - action

- (IBAction)onClickConfigurationBtn:(UIButton *)sender {
    if (!self.inputDomainView.text.length) {
        return;
    }
    
    if (!self.switchBtn.on) {  // 关闭状态，不用请求接口
        [self handleSuccessWithResponse:nil];
        return;
    }
    
    self.indicatorView.hidden = NO;
    [self.indicatorView startAnimating];
    [self requestMapTable];
}

#pragma mark - API

/// 本地服务器获取自定义的匹配信息
- (void)requestMapTable {
    NSString *mapFile = self.inputMapView.text ? : @"config/map.json";
    NSString *url = [self.inputDomainView.text stringByAppendingPathComponent:mapFile];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    
    NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    sessionConfig.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
    
    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig
                                                          delegate:self
                                                     delegateQueue:[FNMockManager shareInstance].delegateQueue];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request];
    [task resume];
}

#pragma mark - NSURLSessionDataDelegate & NSURLSessionTaskDelegate

-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
    completionHandler(NSURLSessionResponseAllow);
 }

 //2.接收到服务器返回数据的时候会调用该方法，如果数据较大那么该方法可能会调用多次
 -(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
     [self.responseData appendData:data];
 }

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.indicatorView stopAnimating];
        self.indicatorView.hidden = YES;
    });
    if(error == nil) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:nil];
        NSLog(@"%@",dict);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self handleSuccessWithResponse:dict];
        });
    }else {
        NSString *tip = error.userInfo[NSLocalizedDescriptionKey] ? : @"请求异常";
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:tip message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

#pragma mark - private

- (void)handleSuccessWithResponse: (NSDictionary *)res {
    [FNMockManager shareInstance].mapTable = res;
    [FNMockManager shareInstance].domain = self.inputDomainView.text;
    [FNMockManager shareInstance].mapPath = self.inputMapView.text;
    BOOL isMock = [FNMockManager shareInstance].isMock;
    [FNMockManager shareInstance].isMock = self.switchBtn.on;
    [[FNMockManager shareInstance] saveConfigToLocal];
    
    [self backAction];
    
    if (isMock == self.switchBtn.on) { // 无改变
        return;
    }

    if (self.switchBtn.on) {
        [[FNMockManager shareInstance] startMock];
    }else {
        [[FNMockManager shareInstance] stopMock];
    }
}

- (void)backAction {
    if (self.navigationController && self.navigationController.viewControllers.count > 1) {
        [self.navigationController popViewControllerAnimated:YES];
    }else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark - getter

- (UIActivityIndicatorView *)indicatorView {
    if (!_indicatorView) {
        _indicatorView = [[UIActivityIndicatorView alloc] init];
        _indicatorView.frame = self.updateButton.frame;
        _indicatorView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.5];
        _indicatorView.color = [UIColor darkGrayColor];
        [self.view addSubview:_indicatorView];
    }
    return _indicatorView;
}

@end
